package com.andong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.andong.domain.entity.Coach;
import com.andong.domain.entity.Student;
import com.andong.domain.entity.Vehicle;
import com.andong.domain.pojo.PageResult;
import com.andong.domain.pojo.Result;
import com.andong.domain.vo.VehicleBookingVO;
import com.andong.utils.BaseContext;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andong.domain.entity.VehicleBooking;
import com.andong.service.VehicleBookingService;
import com.andong.mapper.VehicleBookingMapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import static com.andong.utils.SystemConstant.*;

/**
 * @author 王海云
 * @description 针对表【vehicle_booking(车辆预约表)】的数据库操作Service实现
 * @createDate 2024-01-20 11:08:38
 */
@Service
public class VehicleBookingServiceImpl extends ServiceImpl<VehicleBookingMapper, VehicleBooking>
        implements VehicleBookingService {
    @Override
    public Result insert(VehicleBooking driveBooking) {
        // 只能预约未来一周的时间
        LocalDate date = driveBooking.getBookingTime();
        if (date.isBefore(LocalDate.now()) || date.isAfter(LocalDate.now().plusDays(7))) {
            return Result.error(ONLY_FUTURE_WEEK);
        }
        // 查询这辆车在这个时间点有没有被预约
        Long count = lambdaQuery()
                .eq(VehicleBooking::getVehicleId, driveBooking.getVehicleId())
                .eq(VehicleBooking::getBookingTime, date)
                .count();
        if (count > 0) {
            return Result.error(VEHICLE_BOOKING_ERROR);
        }
        save(driveBooking);
        return Result.success();
    }

    @Override
    public Result getListBy(Integer page, Integer pageSize) {
        // 判断当前是否是学员查询
        Long id = (Long) BaseContext.getCurrentIdAndIdentity().get(CURRENT_ID);
        String identity = (String) BaseContext.getCurrentIdAndIdentity().get(CURRENT_IDENTITY);
        // 构造Student分页器
        Page<VehicleBooking> vehicleBookingPage = new Page<>(page, pageSize);
        List<Long> ids = new ArrayList<>();
        if (COACH.equals(identity)) {
            List<Student> studentList = Db.lambdaQuery(Student.class).eq(Student::getCoachId, id).list();
            ids = studentList.stream().map(Student::getId).toList();
        }
        // 构造Student条件查询器, 得到Student分页查询基本信息结果
        vehicleBookingPage = lambdaQuery()
                .eq(STUDENT.equals(identity), VehicleBooking::getStudentId, id)
                .in(COACH.equals(identity), VehicleBooking::getStudentId, ids)
                .orderByDesc(VehicleBooking::getBookingTime)
                .page(vehicleBookingPage);
        // 使用stream流的方式对记录中的每一条数据进行处理
        List<VehicleBooking> records = vehicleBookingPage.getRecords();
        List<VehicleBookingVO> voList = records.stream().map(recode -> {
            VehicleBookingVO vehicleBookingVO = new VehicleBookingVO();
            BeanUtil.copyProperties(recode, vehicleBookingVO);
            Vehicle vehicle = Db.lambdaQuery(Vehicle.class)
                    .eq(Vehicle::getId, recode.getVehicleId())
                    .one();
            vehicleBookingVO.setPlateNumber(vehicle.getPlateNumber());
            vehicleBookingVO.setImage(vehicle.getImage());
            if (!STUDENT.equals(identity)) {
                Student student = Db.lambdaQuery(Student.class)
                        .eq(Student::getId, recode.getStudentId())
                        .one();
                vehicleBookingVO.setStudentUsername(student.getUsername());
                vehicleBookingVO.setStudentName(student.getName());
                vehicleBookingVO.setStudentPhone(student.getPhone());
                if (!COACH.equals(identity)) {
                    Coach coach = Db.lambdaQuery(Coach.class)
                            .eq(Coach::getId, student.getCoachId())
                            .one();
                    vehicleBookingVO.setCoachUsername(coach.getUsername());
                    vehicleBookingVO.setCoachName(coach.getName());
                }
            }
            return vehicleBookingVO;
        }).toList();
        PageResult result = new PageResult(vehicleBookingPage.getTotal(), voList);
        return Result.success(result);
    }

    @Override
    public Result delete(Long id) {
        removeById(id);
        return Result.success();
    }

    @Override
    public Result updateStatus(Long id, Integer status, String rejectReason) {
        // 查询预约记录
        VehicleBooking vehicleBooking = lambdaQuery()
                .eq(VehicleBooking::getId, id)
                .one();
        LocalDate bookingTime = vehicleBooking.getBookingTime();
        // 查询bookingTime的日期是否在当前日期之前或当天
        if (bookingTime.isBefore(LocalDate.now()) || bookingTime.isEqual(LocalDate.now())) {
            return Result.error(EXPIRED);
        }
        vehicleBooking.setStatus(status);
        vehicleBooking.setRejectReason(rejectReason);
        updateById(vehicleBooking);
        return Result.success();
    }
}




